package com.logan.common;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Controller
@RequestMapping("/")
public class FileUnload {
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	@RequestMapping("upload")
	@ResponseBody
	public Object upload(
			@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, ModelMap model) {
		// TODO 有待改进 不直接使用servlet
		String username = request.getParameter("username");
		String pwd = request.getParameter("userpwd");
		String jsonstr = request.getParameter("jsonstr");
		String cmd = request.getParameter("cmd");
		logger.debug(username + ": " + pwd + ": " + jsonstr);
		String fileName = "";
		String path ="";

		if (!file.isEmpty()) {
			fileName = file.getOriginalFilename();
			logger.debug(fileName);
			File targetFile = new File(path, fileName);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			// 保存
			try {
				file.transferTo(targetFile);
			} catch (Exception e) {

			}
		} else {

		}
		return null;

	}

	@RequestMapping("upload2")
	@ResponseBody
	public Object upload2(
			@RequestParam(value = "file", required = false) CommonsMultipartFile files[],
			HttpServletRequest request, ModelMap model) {
		// TODO 有待改进 不直接使用servlet
		String username = request.getParameter("username");
		String pwd = request.getParameter("userpwd");
		String jsonstr = request.getParameter("jsonstr");
		String cmd = request.getParameter("cmd");
		logger.debug(username + ": " + pwd + ": " + jsonstr);
		String fileName = "";
		String path = "";
		for (CommonsMultipartFile file : files) {
			if (!file.isEmpty()) {
				fileName = file.getOriginalFilename();
				logger.debug(fileName);
				File targetFile = new File(path, fileName);
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				// 保存
				try {
					file.transferTo(targetFile);
				} catch (Exception e) {

				}
			} else {
			}
		}
		return "";

	}
}
